<?php
/**
 * Copyright (c) 2017. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

/*用户模块*/
namespace SDXApi\Controller;
use SDXApi\Model\UsersModel;
use Think\Controller;
use SDXApi\Service\UserBehavior;
class UsersController extends AppController {
   
	public function _initialize(){
		parent::_initialize();
	}
	
	
	
	/*登录*/
    public function login(){
    	$name=I('post.name');
    	if(empty($name)){
    		returnApiError('用户名不能为空');
    	}
        $password=I('post.password');
       if(empty($password)){
    		returnApiError('密码不能为空');
    	}
        $admin_user=M('admin_user');
        $ec_salt=$admin_user->field('ec_salt')->where(array('user_name'=>$name))->find(); 
        if(!empty($ec_salt['ec_salt'])){
        	$password=md5(md5($password).$ec_salt['ec_salt']);
        }else{
        	$password=md5($password);
        }

        $row=$admin_user->field('user_id,user_name,email,add_time')->where(array('user_name'=>$name,'password'=>$password))->find();
        if($row){
        	$warehouse_personnel=M('warehouse_personnel');
        	$wprow=$warehouse_personnel->field('position,wid,longitude,latitude,status')->where(array('uid'=>$row['user_id'],'position'=>2))->find();
        	if($wprow){
	        	$row['position']=$wprow['position'];
	        	$row['wid']=$wprow['wid'];
	        	$row['longitude']=$wprow['longitude'];
	        	$row['latitude']=$wprow['latitude'];
	        	$row['status']=$wprow['status'];
	            $users=array('user'=>$row);
	            $ip=get_client_ip();
	            //记录登录日志
	            $id=$admin_user->where(array('user_id'=>$row['user_id']))->save(array('last_login'=>gmtime(),'last_ip'=>$ip));
	            if($id!=false){
	            	$data=array(
	            	   'log_time'=>gmtime(),
	            	   'user_id'=>$row['user_id'],
	            	   'log_info'=>'配送员APP端：登录',
	            	   'ip_address'=>$ip
	            	);
	            	M('admin_log')->add($data);
	            }
	        	returnApiSuccess($users,'登录成功');
        	}else{
        		returnApiError('该用户没有权限登录');
        	}
        }else{
        	returnApiError('登录失败');
        }
    }
    
    
    /*
     * 修改收货地址时，将地址转换成经纬度并对应入库
     * */
    public function updateaddress(){
    	$user_id=I('post.user_id','intval');
    	$address_id=I('post.address_id','intval');
    	if(!isset($user_id) || !isset($address_id)){
    		returnApiError('参数错误');
    	}
    	$user_address_mod=M('user_address');
    	$where['user_id']=$user_id;
    	$where['address_id']=$address_id;
    	$list=$user_address_mod->where($where)->find();
    	if(count($list)>0){
    		$country_name=$this->get_region_name($list['country']);
        	$province_name=$this->get_region_name($list['province']);
        	$city_name=$this->get_region_name($list['city']);
        	$district_name=$this->get_region_name($list['district']);
        	$address=$country_name.$province_name.$city_name.$district_name.$list['address'];
    		$lnglat=get_lng_lat($address,$city_name);
    		if($lnglat){
    			$longitude=$lnglat['lng'];
    			$latitude=$lnglat['lat'];
    		}else{
    			$longitude='';
    			$latitude='';
    		}
    		$data['longitude']=$longitude;
    		$data['latitude']=$latitude;
    		$id=$user_address_mod->where($where)->save($data);
    		if($id!=false){
    			returnApiSuccess(array('id'=>$id),'修改收货地址时,转换经纬度成功');
    		}else{
    			returnApiError('修改收货地址时,转换经纬度失败');
    		}
    	}else{
    		returnApiError('查无此收货地址');
    	}
    }
    
    
    /*
     * 我的收货地址列表
     * */
    public function my_address_list(){
    	parent::check_uid ();
        $uid=$this->uid;
        $page=I('post.page','intval');
        $list=D('Useraddress')->get_address_list($uid,$page);
//        dd($list);
        if($list){
            /*if($page == 1){
                //添加行为
                $user_bevavior = new UserBehavior();
                $val = $user_bevavior->add_browse($uid, 11);
            }*/
            returnApiSuccess($list);
        }else{
            returnApiError('没有收货地址');
        }
    }
    
    /*
     * 新增我的收货地址
     * */
    public function my_address_add(){
        parent::check_uid ();
       $uid=$this->uid;
       $consignee=I('post.consignee');
       $mobile=I('post.mobile');
       $province=I('post.province');
       $city=I('post.city');
       $district=I('post.district');
       $address=I('post.address');                  //详细地址
       $address_name = I ( 'post.address_name' );   //具体门牌号
       $sign_building = I ( 'post.sign_building' ); //地标
       $sex=I('post.sex');	//1 男  2女
       $address_tag=I('post.address_tag');	//1 家  2公司
       if(!$consignee || !$mobile || !$province || !$city || !$district || !$address){
       	    returnApiError('请完善收货地址信息');
       }
        $address = str_replace($sign_building, '', $address);
        $address = str_replace(array($province."省",$city."市",$district."区"), array('','',''), $address);
        $address = str_replace(array($province,$city,$district), array('','',''), $address);


       //		if(!strstr($address,$sign_building)){
//			$address .= $sign_building;
//		}
        //详细地址中删除地标拼接

        //判断地标和地址是否在一个区域，如不是提示修改
        //$address = ;
        //$lnglat = get_lng_lat($province.$city.$district.$address);
        $lnglat = address_to_gps_amap($address.$sign_building,$district);

        //$lnglat_sign_building = get_lng_lat($province.$city.$district.$sign_building);




//        $User_Mode = new UsersModel();
//
//        $address_mode =  $User_Mode->get_distribution_by_gps($lnglat['lat'],$lnglat['lng']);
//        $building_mode =  $User_Mode->get_distribution_by_gps($lnglat_sign_building['lat'],$lnglat_sign_building['lng']);
//
//
//        if($address_mode['wdr_id']!=$building_mode['wdr_id']){
//            returnApiError('地址有误，请重新选择');
//        }

        if ($lnglat['longitude']>0&&$lnglat['latitude']>0) {
            $longitude = $lnglat['longitude'];
            $latitude = $lnglat['latitude'];
        } else {
            $longitude = 0;
            $latitude = 0;
        }



        $province_id = D('Useraddress')->get_address_id($province, 1);
        $city_id = D('Useraddress')->get_address_id($city, 2);
        $district_id = D('Useraddress')->get_address_id($district, 3);

        if(!$province_id || !$city_id || !$district_id){
            returnApiError('所选地址不在服务范围内，请重新选择');
        }
        $data = array(
            'user_id' => $uid,
            'consignee' => $consignee,
            'country' => 1,
            'province' => $province_id,
            'city' => $city_id,
            'district' => $district_id,
            'address' => $address,
            'address_name' => $address_name,
            'sign_building' => $sign_building,
            'sex' => $sex,
            'address_tag' => $address_tag,
            'mobile' => $mobile
        );

        $data['longitude'] = $longitude;
        $data['latitude'] = $latitude;
        $id = D('Useraddress')->add_address($data);
        if ($id) {
            //加入地标表
            $this->edit_landmark_repair($sign_building,$data['district']);
            //添加用户行为
            $user_behavior = new UserBehavior();
            $user_behavior->add_address($id, 2);

            returnApiSuccess(array('id' => $id), '新增收货地址成功');
        } else {
            returnApiError('新增收货地址失败');
        }
    }
    
    /*
     * 修改我的收货地址
     * */
    
    public function my_address_edit() {
    	parent::check_uid ();
		$uid = $this->uid;
		$address_id = I ( 'post.address_id', 'intval' );
		$consignee = I ( 'post.consignee' );
		$mobile = I ( 'post.mobile' );
		$province = I ( 'post.province' );
		$city = I ( 'post.city');
		$district = I ( 'post.district' );
		$address = I ( 'post.address' );
		$address_name = I ( 'post.address_name' );
		$sign_building = I ( 'post.sign_building' );
        $sex=I('post.sex');	//1 男  2女
        $address_tag=I('post.address_tag');	//1 家  2公司
		if (!$address_id  || !$consignee || !$mobile || !$province || !$city || !$district || !$address) {
			returnApiError ( '请完善收货地址信息' );
		}
		$where ['user_id'] = $uid;
		$where ['address_id'] = $address_id;
		$useraddress = D ( 'Useraddress' );
		
		$address_info = $useraddress->where ( $where )->find ();
        $address = str_replace($sign_building, '', $address);
		$address = str_replace(array($province."省",$city."市",$district."区"), array('','',''), $address);
		$address = str_replace(array($province,$city,$district), array('','',''), $address);


		if ($address_info) {
			$data = array (
					'user_id' => $uid,
					'address_id' => $address_id,
					'consignee' => $consignee,
					'country' => 1,
					'province' => D ( 'Useraddress' )->get_address_id ( $province, 1 ),
					'city' => D ( 'Useraddress' )->get_address_id ( $city, 2 ),
					'district' => D ( 'Useraddress' )->get_address_id ( $district, 3 ),
					'address' => $address,
					'address_name' => $address_name,
					'sign_building' => $sign_building,
					'sex' => $sex,
					'address_tag' => $address_tag,
					'is_ok' => 0,
					'mobile' => $mobile
			);
			$address = $province . $city . $district . $address;
			$lnglat = get_lng_lat ( $address ,$city);
			if ($lnglat) {
				$longitude = $lnglat ['lng'];
				$latitude = $lnglat ['lat'];
			} else {
				$longitude = '';
				$latitude = '';
			}
			$data ['longitude'] = $longitude;
			$data ['latitude'] = $latitude;

            $user_behavior = new UserBehavior();
            //添加用户行为（写入接地址）
            $old_id = $user_behavior->add_address_old($address_id);

			$res = $useraddress->where($where)->save ( $data );
			$result['error_code'] = 100;
			if ($res!==false) {
			    //加入地标表
                $this->edit_landmark_repair($sign_building,$data['district']);
                //添加到用户行为
                $param = array('insertOne', $uid, $address_id, I('wid') , 'edit_address', 1, 1);
                \Think\Hook::listen('receng', $param);

                //添加用户行为
                $user_behavior->add_address($address_id, 1, $old_id);

				returnApiSuccess($result,'修改收货地址成功');
			} else {
				returnApiError ( '修改收获地址失败' );
			}
			
		} else {
			returnApiError ( '查无此收货地址' );
		}
		
		
// 		$count = D ( 'Useraddress' )->get_addresscount ( $where );
// 		if ($count == 1) {
// 			$data = array (
// 					'user_id' => $uid,
// 					'address_id' => $address_id,
// 					'consignee' => $consignee,
// 					'country' => 1,
// 					'province' => D ( 'Useraddress' )->get_address_id ( $province, 1 ),
// 					'city' => D ( 'Useraddress' )->get_address_id ( $city, 2 ),
// 					'district' => D ( 'Useraddress' )->get_address_id ( $district, 3 ),
// 					'address' => $address,
// 					'sex' => $sex,
// 					'mobile' => $mobile 
// 			);
// 			$address = $province . $city . $district . $address;
// 			$lnglat = get_lng_lat ( $address );
// 			if ($lnglat) {
// 				$longitude = $lnglat ['lng'];
// 				$latitude = $lnglat ['lat'];
// 			} else {
// 				$longitude = '';
// 				$latitude = '';
// 			}
// 			$data ['longitude'] = $longitude;
// 			$data ['latitude'] = $latitude;
// 			$id = D ( 'Useraddress' )->edit_address ( $data );
// 			if ($id) {
// 				returnApiSuccess ( array (
// 						'id' => $id 
// 				) );
// 			} else {
// 				returnApiError ( '修改收获地址失败' );
// 			}
// 		} else {
// 			returnApiError ( '查无此收货地址' );
// 		}
	}
		
		/*
	 * 收货地址详情
	 *
	 */
	public function my_address_details() {
		parent::check_uid ();
		$uid = $this->uid;
		$address_id = I ( 'post.address_id', 'intval',0 );
		if (!$address_id) {
			returnApiError ( '参数错误' );
		}
		$useraddress_mod = D ( 'Useraddress' );
		$res = $useraddress_mod->get_address_details ( array (
					'address_id' => $address_id,
					'user_id' => $uid 
			) );
			if ($res) {
				returnApiSuccess ($res);
			} else {
				returnApiError ( '此收货地址不存在' );
			}
	}


    /**
     * 自动加入地标数据表
     * @param null $sign_building 地标
     * @param null $district_id 县区ID
     * @return bool
     */
    private function edit_landmark_repair($sign_building = null, $district_id = null){
	    if(empty($sign_building)||empty($district_id)){
	        return false;   //数据部分不正常，不添加数据
        }
        $where['district_id'] = $district_id;
	    $where['name'] = $sign_building;
        $is_db = M("landmark_repair")->where($where)->count();
        if(empty($is_db)){
            $where['update_time']=gmtime();
            M("landmark_repair")->add($where);
        }
    }

    /*
     * 设定默认收货地址
     * */
    public function my_address_set(){
        parent::check_uid();
        $uid=$this->uid;
       $address_id=I('post.address_id','intval');
       if(!isset($address_id)){
       		returnApiError('参数错误');
       }
       $where['user_id']=$uid;
       $where['address_id']=$address_id;
       $useraddress_mod=D('Useraddress');
       $count=$useraddress_mod->get_addresscount($where);
       if($count==1){
       	   $id=$useraddress_mod->set_address_dafult($uid,$address_id);
       	   if($id){

               //添加行为
               $user_behavior = new UserBehavior();
               $user_behavior->add_address($address_id, 5);

       	   	   returnApiSuccess(array('id'=>$id));
       	   }else{
       	   	  returnApiError('设置默认收获地址失败');
       	   }
       }else{
       	  returnApiError('查无此收货地址');
       }
    }
    
    /*
     * 获取默认收货地址
     * */
    public function my_address_default(){
        parent::check_uid();
        $uid = $this->uid;
        $res = D('Useraddress')->get_address_dafult($uid);
        if ($res) {
            returnApiSuccess($res);
        } else {
            returnApiError('查无此默认收货地址');
        }
    }

    /**
     * 记录用户上次选取的收货地址
     */
    public function set_last_check_address(){
        parent::check_uid();
        $uid = $this->uid;
        $address_id = I('post.address_id');

        if(!empty($uid) && !empty($address_id)){
            S('default_user_address_id_'.$uid,$address_id);
            returnApiSuccess('','记录用户最后选择地址成功');
        }else{
            returnApiError('参数错误');
        }


    }
    
    /*
     * 删除收货地址
     * */
    
    public function my_address_del(){
        parent::check_uid();
        $uid=$this->uid;
       $address_id=I('post.address_id','intval');
       if(!isset($address_id)){
       		returnApiError('参数错误');
       }
       $where['user_id']=$uid;
       $where['address_id']=$address_id;
       $useraddress_mod=D('Useraddress');
       $count=$useraddress_mod->get_addresscount($where);
       if($count==1){

           //添加行为
           $user_behavior = new UserBehavior();
           $user_behavior->add_address($address_id, 6);

       	   $id=$useraddress_mod->del_address($uid,$address_id);
       	   if($id){
       	   	 returnApiSuccess(array('id'=>$id));
       	   }else{
       	   	   returnApiError('删除收货地址失败');
       	   }
       }else{
       	  returnApiError('查无此收货地址');
       }
    }
    
    /*
     * 用户定位
     * */
    public function users_location(){
    	$location=I('post.location',0,'int');
    	if($location==0){
    		parent::check_uid();
    		$uid=$this->uid;
    	}
        $long=I('post.long');
        $lati=I('post.lati');
        $res=D('Users')->set_users_location($uid,$location,$long,$lati);

        if($res['return']){

            $arrival_type = M("distribution_mode")->where(array("id"=>$res['mode_id']))->getField("arrival_type");

            $res['is_day'] = (string)$arrival_type;
//            if($_POST['is_app'] ==1){
//                if($res['is_day'] == 1){
//                    $res['is_day'] =0;
//                }elseif($res['is_day'] == 0){
//                    $res['is_day'] =1;
//                }
//            }
            if($res['name']==-1){
                $res['is_day'] = '-1';
            }

            //查询是否为196用户
            $is_891 = M('users')->where(array('user_id' => $uid))->getField('is_891');
            //196用户：仓库id用主仓对应的虚拟仓
            if($is_891 == 2){
                $res['wid'] = M('warehouse')->where(array('pid' => $res['wid']))->getField('id');
            }

            returnApiSuccess(array('distribution'=>$res));
        }else{
            returnApiError('用户定位失败',$res);
        }
    }

	/**
	 * Created by Jerry
	 */
	public function get_gps_address_time()
	{
		$location=I('post.location',0,'int');
		$long = I('post.longitude', 0);
		$lati = I('post.lati', 0);
		$uid = I('post.uid', 0, 'int');

		$address = D('Users')->get_goods_info_address_time($uid, $location, $long, $lati);

		if (empty($address)) {
			returnApiError('获取地址信息失败');
		}

		returnApiSuccess($address);
	}

	/*
 * 用户定位--根据地址内容
 * */
	public function users_location_by_address(){
		//parent::check_uid();
		$address=I('post.address');


//		$data=address_to_gps(str_ireplace(' ','',$address));
//		$latitude=$data['latitude'];
//		$longitude=$data['longitude'];
//		$arr=D('Users')->get_distribution_by_gps($longitude, $latitude);


		$date = address_to_gps_amap($address);
		//dump($address);
		//dump($date);
		$res=D('Users')->set_users_location(null,1,$date['longitude'],$date['latitude']);
		if($res['return']){
		    $data['distribution'] = $res;
		    $data['dis_time'] = $res['dis_time'];
			returnApiSuccess($data,"数据已返回");
		}else{
			returnApiError('用户定位失败',$res);
		}
	}
    /*
     * 获取用户收货地址转经纬度
     * */
    
    public function address_conversion(){
        parent::check_uid();
        $uid=$this->uid;
        $address=I('post.address');
        $res=D('Users')->get_address_conversion($address);
        returnApiSuccess(array('longlati'=>$res));
    }
    
    /*
     * 根据订单收货地址获取对应仓库ID
     * */
    public function order_shipping_address_get_wid(){
        $order_id=I('post.order_id');
        $user_id=I('post.user_id');
        if(empty($order_id) || empty($user_id)){
            returnApiError('参数错误');
        }
        $order=M('order_info')->where(array('order_id'=>$order_id,'user_id'=>$user_id))->find();
        if($order){
            $country = M('region')->where('region_id ='.$order['country'])->getField('region_name');
            $province = M('region')->where('region_id ='.$order['province'])->getField('region_name');
            $city = M('region')->where('region_id ='.$order['city'])->getField('region_name');
            $district = M('region')->where('region_id ='.$order['district'])->getField('region_name');
            $all_address = $country.$province.$city.$district.$order['address'];
            $gps=address_to_gps_amap($all_address);
            $res=D('Users')->get_distribution_by_gps($gps['longitude'],$gps['latitude']);
            returnApiSuccess(array('data'=>$res));
        }else{
            returnApiError('此订单不存在');
        }
    }
    
   /*根据ID获取区域对应名称*/
    private  function get_region_name($id){
    	$res=M('region')->where(array('region_id'=>$id))->find();
    	return $res['region_name'];
    }

    /**
     * 根据地标获取纠错地址GPS
     */
    public function get_gps_by_sign_building(){
        $sign_building = I("post.sign_building");
        if($sign_building){
            $sign_building_gps = M('louxiaoer_landmark')->field("lat,lng")->where(array("name"=>$sign_building,"is_check"=>1))->find();
            if($sign_building_gps){
                returnApiSuccess($sign_building_gps);
            }else{

                returnApiError("no rec");
            }
        }
    }

	/**
	 * Created by Jerry
	 */
	public function get_goods_info_address_message()
	{
		$ad = I('post.ad', 0, 'int');
		$addressId = I('post.address_id', 0, 'int');

        $ms = array();
		if ($ad == 3) {
			$ms = D('LouxiaoerOrder')->findLouxiaoerByAddressId($addressId);
		}

        $data['wechat_barcode_img'] = '';
        $data['louguanjia'] = 'SDXSG6';
		$adMessage = null;
		switch ($ad) {
			case 1:
				$adMessage = '收到货后如发现商品有异常，生鲜食品可在签收后24小时内拍照提交售后工单，我们将为您进行处理！';
				break;
			case 2:
				$adMessage = '收到货后如发现商品有异常，生鲜食品可在签收后24小时内拍照提交售后工单，我们将为您进行处理！';
				break;
			case 3:
                if (empty($ms['name'])) {
                    $adMessage = "收到货后如发现商品有异常，生鲜食品可在签收后24小时内拍照提交售后工单，我们将为您进行处理!";
                }
                else{
//                    $adMessage = "下单后添加楼管家微信订单最高可返8元。您的专属客服楼管家为{$ms['name']}-{$ms['phone']}。";
                    $adMessage = "收到货后如发现商品有异常，生鲜食品可在签收后24小时内拍照提交售后工单，我们将为您进行处理!";

                    if (! empty($ms['wechat_barcode_img'])) {
                        $data['wechat_barcode_img'] = 'https://image.shidexian.com/' . $ms['wechat_barcode_img'];
                    }

                    if (! empty($ms['name'])) {
                        $data['louguanjia'] = $ms['wechat_name'];
                    }
                }
				break;
		}

		if (is_null($adMessage)) {
			returnApiError('暂无广告信息');
		}

		$data['ad_message'] = $adMessage;

		returnApiSuccess($data);
	}

	public function send_bonus(){
        //确认收货，赠送红包
        $user_id = I('post.uid');
        $order_id = I('post.order_id');

        if(!empty($order_id) && !empty($user_id)){
            D('Userbonus')->send_bonus_to_user($user_id,$order_id);
        }
    }

    public function send_bonus_for12(){
        //双12首单送红包
        $user_id = I('post.uid');
        $order_id = I('post.order_id');

        if(!empty($order_id) && !empty($user_id)){
            D('Userbonus')->send_bonus_for_d12($user_id,$order_id);
        }
    }

    public function cancel_bonus_for_d12(){
        //双12当天取消订单回收红包
        $user_id = I('post.uid');
        $order_id = I('post.order_id');

        if(!empty($order_id) && !empty($user_id)){
            D('Userbonus')->cancel_bonus_for_d12($user_id,$order_id);
        }
    }
    
    
}
